package cn.edu.fzu.homemaking.service.impl;

import cn.edu.fzu.homemaking.api.SysApi;
import cn.edu.fzu.homemaking.common.EmailMessageTemplate;
import cn.edu.fzu.homemaking.common.Sn;
import cn.edu.fzu.homemaking.common.UnPayStatusList;
import cn.edu.fzu.homemaking.domain.entity.DateCount;
import cn.edu.fzu.homemaking.domain.entity.Order;
import cn.edu.fzu.homemaking.domain.entity.Statistics;
import cn.edu.fzu.homemaking.domain.entity.SysCompanyDTO;
import cn.edu.fzu.homemaking.domain.enums.CommentStatusEnum;
import cn.edu.fzu.homemaking.domain.enums.OrderStatusEnum;
import cn.edu.fzu.homemaking.domain.vo.OrderVo;
import cn.edu.fzu.homemaking.exception.ServiceException;
import cn.edu.fzu.homemaking.helper.EmailHelper;
import cn.edu.fzu.homemaking.mapper.OrderMapper;
import cn.edu.fzu.homemaking.service.OrderService;
import cn.edu.fzu.homemaking.util.ResultUtil;
import cn.edu.fzu.homemaking.web.Result;
import com.google.common.base.Objects;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author jiebin
 * @date 2023/4/11
 */
@Service("orderService")
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private SysApi sysApi;

    @Resource
    private EmailHelper emailHelper;

    @Override
    public void insert(Long companyId, Long userId, Long demandId, Long serverId, String description, String customerName,
                       String address, String phone, String email, String startTime, BigDecimal price, Integer qty) {
        String orderId = Sn.next().substring(0,20);
        orderMapper.insert(orderId, companyId,userId, demandId, serverId, description, customerName, address, phone,
                email, startTime, price, qty, OrderStatusEnum.ORDER, CommentStatusEnum.NO);
        emailHelper.sendMail(email,"订单状态发生改变","亲爱的"+customerName+"先生/女士，"+EmailMessageTemplate.getValue(OrderStatusEnum.ORDER));
    }

    @Override
    public List<OrderVo> list(Long companyId, Long userId, Long demandId, Long serverId, String startTime,
                            String endTime, OrderStatusEnum status, CommentStatusEnum commentStatus) {
        List<Order> orders = orderMapper.list(companyId, userId, demandId, serverId, startTime, endTime, status, commentStatus);
        SysCompanyDTO companyDTO = new SysCompanyDTO();
        if (companyId != null){
            Result result = sysApi.getById(companyId);
            companyDTO = ResultUtil.parseValue(result, SysCompanyDTO.class);
        }
        List<OrderVo> list = new ArrayList<>();
        for (Order order: orders) {
            OrderVo orderVo = new OrderVo();
            BeanUtils.copyProperties(order,orderVo);
            if (companyId != null){
                orderVo.setCompanyName(companyDTO.getName());
            }else{
                Result result = sysApi.getById(order.getCompanyId());
                SysCompanyDTO sysCompanyDTO = ResultUtil.parseValue(result, SysCompanyDTO.class);
                orderVo.setCompanyName(sysCompanyDTO.getName());
            }
            list.add(orderVo);
        }
        return list;
    }

    @Override
    public BigDecimal getUnPayMoney(Long usrId) {
        List<Order> list = orderMapper.listUnPayByUserId(UnPayStatusList.getUnPayStatusList(),usrId);
        BigDecimal money = new BigDecimal(0);
        for (Order order: list) {
            money = money.add(order.getPrice().multiply(new BigDecimal(order.getQty())));
        }
        return money;
    }

    @Override
    public void updateStatus(String orderId, OrderStatusEnum status, Long customerId, Long companyId) {
        Order order = orderMapper.selectByOrderId(orderId);
        if (customerId!=null){
            if ((!Objects.equal(order.getStatus(),OrderStatusEnum.ORDER) && !Objects.equal(order.getStatus(),OrderStatusEnum.PAYING)) ||
                    (!Objects.equal(status,OrderStatusEnum.CANCEL) && !Objects.equal(status,OrderStatusEnum.ENDED))){
                throw new ServiceException("无法更新订单状态");
            }
        }else if (companyId !=null){
            if (!Objects.equal(companyId,order.getCompanyId())){
                throw new ServiceException("公司无法修改不属于本公司的订单");
            }
        }
        orderMapper.updateStatus(orderId, status);
        emailHelper.sendMail(order.getEmail(),"订单状态发生改变","亲爱的"+order.getCustomerName()+"先生/女士，"+
                EmailMessageTemplate.getValue(status));
    }

    @Override
    public void updateCommentStatus(String orderId, CommentStatusEnum commentStatus) {
        orderMapper.updateCommentStatus(orderId, commentStatus);
    }

    @Override
    public OrderVo selectByOrderId(String orderId) {
        Order order = orderMapper.selectByOrderId(orderId);
        OrderVo orderVo = new OrderVo();
        BeanUtils.copyProperties(order, orderVo);
        Result result = sysApi.getById(order.getCompanyId());
        SysCompanyDTO sysCompanyDTO = ResultUtil.parseValue(result, SysCompanyDTO.class);
        orderVo.setCompanyName(sysCompanyDTO.getName());
        return orderVo;
    }

    @Override
    public List<Order> listByOrderIds(List<String> orderIds, String startTime, String endTime, OrderStatusEnum status) {
        return orderMapper.listByOrderIds(orderIds, startTime, endTime, status);
    }

    @Override
    public Statistics count(String startTime, String endTime, Long companyId) {
        Statistics statistics = new Statistics();
        Long receive = orderMapper.count(startTime, endTime, null,null, companyId);
        Long complete = orderMapper.count(startTime, endTime, null, OrderStatusEnum.ENDED,companyId);
        Long demandNum = orderMapper.count(startTime, endTime, true, null, companyId);
        statistics.setReceive(receive);
        statistics.setComplete(complete);
        statistics.setUnComplete(receive-complete);
        statistics.setDemandNum(demandNum);
        return statistics;
    }

    @Override
    public List<DateCount> countByMonth(String startTime, String endTime, Long companyId) {
        return orderMapper.countByMonth(startTime, endTime, companyId);
    }

    @Override
    public List<DateCount> countByDay(String startTime, String endTime, Long companyId) {
        return orderMapper.countByDay(startTime, endTime, companyId);
    }


}
